<?php

namespace app\common\requests;

use think\exception\ValidateException;

abstract class PackingRequest
{

    public $realRequest;

    public $userId;

    protected $array_msg = [];
    protected $array_rule = [];

    public function __construct()
    {
        $this->realRequest = request();
        $this->userId     = $this->realRequest->userId ?? 0;
    }

//    public function __call($name, $arguments)
//    {
//        return $this->realRequest->$name($arguments);
//    }

    /**
     * @param array $other 额外验证或者场景验证
     * @param bool $array 是否验证数组规则
     * @return array
     * @author yashuai<1762910894@qq.com>
     */
    public function getValidationData(array $other = [], bool $array = true)
    {
        $params = $this->realRequest->all();
        $rules  = $this->getRules($other);
        $this->validatorData($rules, $this->message(), $params);
        if (!empty($this->array_rule) && $array) {
            $this->validatorArray($params);
        }
        return $params;
    }

    public abstract function rules();

    public abstract function message();

    /**
     * @Desc 获取验证规则
     * @param array|string $other
     * @return array
     * @author yashuai<1762910894@qq.com>
     */
    private function getRules(array $other = [])
    {
        $baseRules = $this->rules();
        $rules     = [];
        if (!empty($other)) {
            if (is_array($other)) {
                $rules = array_merge($baseRules, $other);
            } else if (is_string($other) && isset($this->scene[$other])) {
                foreach ($this->scene[$other] as $val) {
                    $rules[$val] = $baseRules[$val];
                }
            }
        } else {
            $rules = $baseRules;
        }
        return $rules;
    }

    /**
     * @Desc 验证数组
     * @param $params
     * @author yashuai<1762910894@qq.com>
     */
    private function validatorArray($params)
    {
        foreach ($this->array_rule as $field => $rule) {
            if (_array_field($params, $field)) {
                if (count($params[$field]) == count($params[$field], 1)) {
                    $this->validatorData($rule, $this->array_msg[$field], $params[$field]);
                } else {
                    foreach ($params[$field] as $paramsVal) {
                        $this->validatorData($rule, $this->array_msg[$field], $paramsVal);
                    }
                }
            }
        }
    }

    /**
     * @Desc 验证
     * @param $rules
     * @param $message
     * @param $params
     * @author yashuai<1762910894@qq.com>
     */
    private function validatorData($rules, $message, $params)
    {
        try {
            Validate()->rule($rules)->message($message)->check($params);
        } catch (ValidateException $validate) {
            _throw($validate->getError(), 106002);
        }
    }

}
